package com.zhangxu.microservice.auth.vo.resp;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 分页响应
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class PageResponse<T> implements Serializable {

    @Schema(description = "当前页")
    private Integer currentPage;
    @Schema(description = "每页大小")
    private Integer pageSize;
    @Schema(description = "总记录数")
    private Long total;
    @Schema(description = "总页数")
    private Long pages;
    @Schema(description = "数据列表")
    private List<T> items;

    /**
     * 将MyBatis-Plus分页结果转换为通用分页响应
     *
     * @param page     MyBatis-Plus分页结果
     * @param function 转换函数
     * @param <T>      目标类型
     * @param <R>      源类型
     * @return 通用分页响应
     */
    public static <T, R> PageResponse<T> convert(IPage<R> page, Function<R, T> function) {
        if (page == null) {
            return new PageResponse<>();
        }
        List<T> collect = page.getRecords().stream().map(function).collect(Collectors.toList());
        return PageResponse.<T>builder()
                .currentPage((int) page.getCurrent())
                .pageSize((int) page.getSize())
                .total(page.getTotal())
                .pages(page.getPages())
                .items(collect)
                .build();
    }

    /**
     * 空分页结果
     *
     * @param <T> 类型
     * @return 空分页响应
     */
    public static <T> PageResponse<T> empty() {
        return PageResponse.<T>builder()
                .currentPage(1)
                .pageSize(10)
                .total(0L)
                .pages(0L)
                .items(Collections.emptyList())
                .build();
    }
}